package com.ominext.twitter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.ominext.beautifulcapture.R;
import com.ominext.facebook.HomeFacebook;
import com.ominext.home.HomeActivity;
import com.ominext.home.Path;

@SuppressLint("NewApi")
public class TwitterHome extends Activity {

	// Constants
	/**
	 * Register your here app https://dev.twitter.com/apps/new and get your
	 * consumer key and secret
	 * */
	static String TWITTER_CONSUMER_KEY = "ilKuf05zohhfoEtG1lQqnQ"; // place your
																	// cosumer
																	// key here
	static String TWITTER_CONSUMER_SECRET = "BrlpZCws1ghMsRMfozMiWs8JAbzDQwHwKUuPOxZEo"; // place
																							// your
																							// consumer
																							// secret
																							// here

	// Preference Constants
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

	static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	// Twitter oauth urls
	static final String URL_TWITTER_AUTH = "auth_url";
	static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	// Button
	Button mUser;
	Button mButtonLogout;
	Button mButtonUpload;
	Button mButtonCancel;

	// EditText
	EditText mStatus;

	// ImageView
	ImageView mImageUpload;

	// Progress dialog
	ProgressDialog pDialog;

	// Twitter
	private static Twitter twitter;
	private static RequestToken requestToken;

	// Shared Preferences
	private static SharedPreferences mSharedPreferences;

	// Internet Connection detector
	private ConnectionDetector cd;

	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tw_upload_photo);
		if (Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(TwitterHome.this,
					"Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}

		// Check if twitter keys are set
		if (TWITTER_CONSUMER_KEY.trim().length() == 0
				|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
			// Internet Connection is not present
			alert.showAlertDialog(TwitterHome.this, "Twitter oAuth tokens",
					"Please set your twitter oauth tokens first!", false);
			// stop executing code by return
			return;
		}

		mUser = (Button) findViewById(R.id.user_tw);
		mButtonLogout = (Button) findViewById(R.id.logout_tw);
		mButtonUpload = (Button) findViewById(R.id.up_to_tw);
		mButtonCancel = (Button) findViewById(R.id.cancel_tw);

		// EditText
		mStatus = (EditText) findViewById(R.id.status_photo_tw);

		// ImageView
		mImageUpload = (ImageView) findViewById(R.id.imageViewUpload_tw);
		mImageUpload.setImageBitmap(BitmapFactory
				.decodeFile(Path.imageShowPath));

		// Shared Preferences
		mSharedPreferences = getApplicationContext().getSharedPreferences(
				"MyPref", 0);
		/**
		 * This if conditions is tested once is redirected from twitter page.
		 * Parse the uri to get oAuth Verifier
		 * */
		loginToTwitter();
		if (!isTwitterLoggedInAlready()) {
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
				// oAuth verifier
				String verifier = uri
						.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

				try {
					// Get the access token
					AccessToken accessToken = twitter.getOAuthAccessToken(
							requestToken, verifier);

					// Shared Preferences
					Editor e = mSharedPreferences.edit();

					// After getting access token, access token secret
					// store them in application preferences
					e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(PREF_KEY_OAUTH_SECRET,
							accessToken.getTokenSecret());
					// Store login status - true
					e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
					e.commit(); // save changes

					Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

					mUser.setVisibility(View.VISIBLE);
					mButtonCancel.setVisibility(View.VISIBLE);
					mButtonUpload.setVisibility(View.VISIBLE);
					mButtonLogout.setVisibility(View.VISIBLE);
					mStatus.setVisibility(View.VISIBLE);
					mImageUpload.setVisibility(View.VISIBLE);

					// Getting user details from twitter
					// For now i am getting his name only
					long userID = accessToken.getUserId();
					User user = twitter.showUser(userID);
					String username = user.getName();

					// Displaying in xml ui
					mUser.setText(Html.fromHtml("<b>Welcome " + username
							+ "</b>"));
				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
				}
			}
		}

		mButtonUpload.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				uploadImage();
			}
		});

		mButtonLogout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// logoutFromFacebook();
				logoutFromTwitter();
				Intent intent = new Intent(TwitterHome.this, HomeActivity.class);
				startActivity(intent);
			}
		});

		mButtonCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(TwitterHome.this, HomeActivity.class);
				startActivity(intent);
			}
		});

	}

	/**
	 * Function to login twitter
	 * */
	private void loginToTwitter() {
		// Check if already logged in
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();

			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();
			if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)) {
				try {
					requestToken = twitter
							.getOAuthRequestToken(TWITTER_CALLBACK_URL);
					this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
							.parse(requestToken.getAuthenticationURL())));
				} catch (TwitterException e) {
					e.printStackTrace();
				}
			} else {
				new Thread(new Runnable() {
					public void run() {
						try {
							requestToken = twitter
									.getOAuthRequestToken(TWITTER_CALLBACK_URL);
							TwitterHome.this.startActivity(new Intent(
									Intent.ACTION_VIEW, Uri.parse(requestToken
											.getAuthenticationURL())));
						} catch (TwitterException e) {
							e.printStackTrace();
						}
					}
				}).start();
			}
		} else {
			// user already logged into twitter
			Toast.makeText(getApplicationContext(),
					"Already Logged into twitter", Toast.LENGTH_LONG).show();
			mUser.setVisibility(View.VISIBLE);
			mButtonCancel.setVisibility(View.VISIBLE);
			mButtonUpload.setVisibility(View.VISIBLE);
			mButtonLogout.setVisibility(View.VISIBLE);
			mStatus.setVisibility(View.VISIBLE);
			mImageUpload.setVisibility(View.VISIBLE);

		}
	}

	private void logoutFromTwitter() {
		// Clear the shared preferences
		Editor e = mSharedPreferences.edit();
		e.remove(PREF_KEY_OAUTH_TOKEN);
		e.remove(PREF_KEY_OAUTH_SECRET);
		e.remove(PREF_KEY_TWITTER_LOGIN);
		e.commit();

		// After this take the appropriate action
		// I am showing the hiding/showing buttons again
		// You might not needed this code

	}

	/**
	 * Check user already logged in your application using twitter Login flag is
	 * fetched from Shared Preferences
	 * */
	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
	}

	protected void onResume() {
		super.onResume();
	}

	public void uploadImage() {
		// String status = args[0];
		StatusUpdate status = new StatusUpdate(mStatus.getText().toString());
		try {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

			// Access Token
			String access_token = mSharedPreferences.getString(
					PREF_KEY_OAUTH_TOKEN, "");
			// Access Token Secret
			String access_token_secret = mSharedPreferences.getString(
					PREF_KEY_OAUTH_SECRET, "");

			AccessToken accessToken = new AccessToken(access_token,
					access_token_secret);
			Twitter twitter = new TwitterFactory(builder.build())
					.getInstance(accessToken);
			Bitmap bmp = BitmapFactory.decodeFile(Path.imageShowPath);
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
			byte[] byteArray = stream.toByteArray();
			ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
			// StatusUpdate status = new StatusUpdate(message);
			status.setMedia("newyear", bis);

			// Update status
			// twitter4j.Status response = twitter.updateStatus(status);
			twitter.updateStatus(status);
			Toast.makeText(getApplicationContext(), "uploading....",
					Toast.LENGTH_LONG).show();
			// Log.d("Status", "> " + response.getText());
		} catch (TwitterException e) {
			// Error in updating status
			Log.d("Twitter Update Error", e.getMessage());
		}
	}

}
